package com.green.common.util;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class StringUtil {
	/**
	 * 将byte数组转换为表示16进制值的字符串， 如：byte[]{8,18}转换为：0813， 和public static byte[]
	 * hexStr2ByteArr(String strIn) 互为可逆的转换过程
	 * 
	 * @param arrB
	 *            需要转换的byte数组
	 * @return 转换后的字符串
	 * @throws Exception
	 *             本方法不处理任何异常，所有异常全部抛出
	 * @author <a href="mailto:zhangji@aspire-tech.com">ZhangJi</a>
	 */
	public static String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		// 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * 将表示16进制值的字符串转换为byte数组， 和public static String byteArr2HexStr(byte[] arrB)
	 * 互为可逆的转换过程
	 * 
	 * @param strIn
	 *            需要转换的字符串
	 * @return 转换后的byte数组
	 * @throws Exception
	 *             本方法不处理任何异常，所有异常全部抛出
	 * @author <a href="mailto:zhangji@aspire-tech.com">ZhangJi</a>
	 */
	public static byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

	/**
	 * @param str
	 *            the string need to be parsed
	 * @param delim
	 *            the delimiter to seperate created by YanFeng at 14/5/2003
	 */
	public static String[] parseToArray(String str, String delim) {
		ArrayList arr = new ArrayList();
		StringTokenizer st = new StringTokenizer(str, delim);
		while (st.hasMoreTokens()) {
			arr.add(st.nextToken());
		}
		String[] ret = new String[arr.size()];
		for (int i = 0; i < arr.size(); i++) {
			ret[i] = (String) arr.get(i);
		}
		return ret;
	}

	/**
	 * replace a old substring with rep in str
	 * 
	 * @param str
	 *            the string need to be replaced
	 * @param old
	 *            the string need to be removed
	 * @param rep
	 *            the string to be inserted
	 * @return string replaced
	 */
	public static String replace(String str, String old, String rep) {
		if (str == null || old == null || rep == null) {// if one is null return
														// ""
			return "";
		}
		int index = str.indexOf(old);
		if (index < 0 || old.equals("")) { // if no old string found or nothing
											// to replace,return the origin
			return str;
		}
		StringBuffer strBuf = new StringBuffer(str);
		while (index >= 0) { // found old part
			strBuf.delete(index, index + old.length());
			strBuf.insert(index, rep);
			index = strBuf.toString().indexOf(old);
		}
		return strBuf.toString();
	}

	/**
	 * 带逗号分隔的数字转换为NUMBER类型
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Number stringToNumber(String str) throws ParseException {
		if (str == null || str.equals("")) {
			return null;
		}
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setDecimalSeparator('.');
		dfs.setGroupingSeparator(',');
		dfs.setMonetaryDecimalSeparator('.');
		DecimalFormat df = new DecimalFormat("###,###,###,###.##", dfs);
		return df.parse(str);
	}

	public static String getExtensionName(String filename) {
		if (filename != null && filename.length() > 0) {
			int dot = filename.lastIndexOf('.');
			if (dot > -1 && dot < filename.length() - 1) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	public static String valueOf(Object obj) {
		if (obj == null) {
			return null;
		}
		return String.valueOf(obj);
	}

	/**
	 * 用于字符串替换
	 * 
	 * @param target
	 *            目标对象 需要替换的字符串
	 * @param replacement
	 *            要替换的字符串
	 * @param value
	 *            替换的值
	 * @return
	 */
	public static String replacement(String target, String replacement, String value) {
		if (target != null) {
			return target.replace(replacement, value);
		}
		return null;
	}

	/**
	 * 判断字符串是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		if (str == null || str.length() == 0) {
			return false;
		}
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 计算指定时间与当前时间的差
	 * 
	 * @param date
	 * @return
	 */
	public static String convDateToString(Date date) {
		Long time = new Date().getTime() - date.getTime();
		Long min = time / 1000 / 60;
		if (min < 5) {
			return "刚刚";
		} else if (min >= 5 && min < 60) {
			return min + "分钟之前";
		} else if (min >= 60 && min < 1440) {
			return min / 60 + "小时之前";
		} else if (min >= 1440 && min < 10080) {
			return min / 60 / 24 + "天之前";
		} else if (min >= 10080 && min < 40320) {
			return min / 60 / 24 / 7 + "周之前";
		} else if (min >= 40320 && min < 525600) {
			return min / 60 / 24 / 7 / 4 + "月之前";
		} else if (min >= 525600) {
			return min / 60 / 24 / 365 + "年之前";
		}
		return null;
	}
	
	public static String convNullToValue(String str,String value){
		if(str==null){
			return value;
		}
		return str;
	}

	/**
	 * 把手机号码中的中间四位用*号代替
	 * 
	 * @param phone
	 * @returnStringUtil
	 */
	public static String securityPhone(String phone) {
		if (phone == null || phone.equals("")) {
			return "";
		}
		if (phone.length() < 11) {
			return phone;
		}
		String tempStr = "";
		tempStr = phone.substring(0, phone.length() - 4);
		return tempStr + "****";
	}

	/**
	 * 字符串是不是为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (null == str || str.trim().length() < 1) {
			return true;
		}
		return false;
	}

	/**
	 * 将 空格 替换成加号 , fid 传到页面的时候会将加号变成空格，这个方法是将其变回原来的样子 added by taking.wang
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceSpaceToAddChar(String str) {
		if (isEmpty(str)) {
			return null;
		}
		return str.replaceAll(" ", "+");
	}

	/**
	 * 转换html标记
	 * 
	 * @return
	 */
	public static String html(String html) {
		if (html == null || html.equals("")) {
			return null;
		}
		StringBuffer result = null;
		String filtered = null;
		for (int i = 0; i < html.length(); ++i) {
			filtered = null;
			switch (html.charAt(i)) {
			case '<':
				filtered = "&lt;";
				break;
			case '>':
				filtered = "&gt;";
				break;
			case '&':
				filtered = "&amp;";
				break;
			case '"':
				filtered = "&quot;";
				break;
			case '\'':
				filtered = "&#39;";
			}
			if (result == null) {
				if (filtered != null) {
					result = new StringBuffer(html.length() + 50);
					if (i > 0) {
						result.append(html.substring(0, i));
					}
					result.append(filtered);
				}

			} else if (filtered == null) {
				result.append(html.charAt(i));
			} else {
				result.append(filtered);
			}
		}

		return ((result == null) ? html : result.toString());
	}

	/**
	 * 得到一个字符窜标识的内容
	 * 
	 * @param str
	 * @param markeStr
	 * @return
	 */
	public static String getMarkeContent(String str, String markeBegin, String markeEnd) {
		return StringUtil.getMarkeContent(str, markeBegin, markeEnd, null);
	}

	/**
	 * 得到一个字符窜标识的内容
	 * 
	 * @param str
	 * @param markeStr
	 * @return
	 */
	public static String getMarkeContent(String str, String markeBegin, String markeEnd, String defualtValue) {
		if (StringUtil.isEmpty(str)) {
			return defualtValue;
		}
		if (StringUtil.isEmpty(markeBegin)) {
			return defualtValue;
		}
		int beginIndex = str.indexOf(markeBegin);
		int endIndex = str.lastIndexOf(markeEnd);
		if (beginIndex < 0 || endIndex < 0 || endIndex <= beginIndex) {
			return defualtValue;
		}
		return str.substring(beginIndex + 1, endIndex);
	}

	/**
	 * 得到一个字符排除标识中的内容
	 * 
	 * @param str
	 * @param markeStr
	 * @return
	 */
	public static String getNotMarkeContent(String str, String markeBegin, String markeEnd) {
		if (StringUtil.isEmpty(str)) {
			return null;
		}
		if (StringUtil.isEmpty(markeEnd)) {
			return str;
		}
		int endIndex = str.lastIndexOf(markeEnd) + 1;
		return str.substring(endIndex);
	}

	/**
	 * 所以的参数多不为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotEmpty(String... strs) {
		if (strs == null || strs.length <= 0) {
			return false;
		}
		for (String str : strs) {
			if (StringUtil.isEmpty(str)) {
				return false;
			}
		}
		return true;
	}

	public static boolean isEmpty(Object obj) {
		if (null == obj) {
			return true;
		}
		return String.valueOf(obj).trim().length() < 1;
	}
	
	/*
	  * 判断是否为整数 
	  * @param str 传入的字符串 
	  * @return 是整数返回true,否则返回false 
	*/
	 
	  public static boolean isInteger(String str) {  
		if(!isEmpty(str)){
			Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");  
		    return pattern.matcher(str).matches();  
		}
	    return Boolean.FALSE;
	  }

	  /* 
	   * 判断是否为浮点数，包括double和float 
	   * @param str 传入的字符串 
	   * @return 是浮点数返回true,否则返回false 
	 */ 
	   public static boolean isDouble(String str) {  
		   if(!isEmpty(str)){
			   Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]+$");  
			     return pattern.matcher(str).matches();  
		   }
		   return Boolean.FALSE;
	   }
	   
	  /* 
	   * 判断是否为数字类型
	   * @param str 传入的字符串 
	   * @return 是数字类型返回true,否则返回false 
	 */ 
	   public static boolean isNumber(String str) {  
		   if(!isEmpty(str)){
			   return isDouble(str) || isInteger(str);
		   }
		   return Boolean.FALSE;
	   }
		   
	   /**
		 * 过滤html相关标签
		 * @param htmlStr
		 * @return
		 */   
	   public static String getHtmlString(String htmlStr){
	        String textStr = "";      
	        java.util.regex.Pattern p_script;      
	        java.util.regex.Matcher m_script;      
	        java.util.regex.Pattern p_style;      
	        java.util.regex.Matcher m_style;      
	        java.util.regex.Pattern p_html;      
	        java.util.regex.Matcher m_html;      
	    
	        java.util.regex.Pattern p_html1;      
	        java.util.regex.Matcher m_html1;      
	    
	       try {      
	            String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>      
	            String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>      
	            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式      
	            String regEx_html1 = "<[^>]+";      
	            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);      
	            m_script = p_script.matcher(htmlStr);      
	            htmlStr = m_script.replaceAll(""); // 过滤script标签      
	    
	            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);      
	            m_style = p_style.matcher(htmlStr);      
	            htmlStr = m_style.replaceAll(""); // 过滤style标签      
	    
	            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);      
	            m_html = p_html.matcher(htmlStr);      
	            htmlStr = m_html.replaceAll(""); // 过滤html标签      
	    
	            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);      
	            m_html1 = p_html1.matcher(htmlStr);      
	            htmlStr = m_html1.replaceAll(""); // 过滤html标签      
	    
	            textStr = htmlStr;      
	    
	        } catch (Exception e) {      
	            System.err.println("Html2Text: " + e.getMessage());      
	        }      
	    
	      return textStr;// 返回文本字符串      
	}
	   
	public static boolean matches(String regex,String value){
		if(StringUtil.isEmpty(regex)||StringUtil.isEmpty(value)){
			return false;
		}
		return value.matches(regex);
	}
	   
	public static void main(String[] args) {

		String ss = "fdsafd";
		System.out.println(getNotMarkeContent(ss, "[", "]"));
		System.out.println(isDouble("-1"));
		System.out.println(isInteger("-1"));

	}

	
	public static String filterHtmlElement(String target) {
        target = target.trim();
        target = target.replace("<", "&lt;");
        target = target.replace(">", "&gt;");
        target = target.replace("\n", "<br>");
        target = target.replace("\"", "&quot;");
        target = target.replace("\'", "&#039;");
        return target.replaceAll("'|exec |;|--|\\/\\*|\\*\\/", "");
    }
    
}
